package demo.thread;

import java.util.ArrayList;
import java.util.List;

public class Test1 {
	public static List<String> list = new ArrayList<String>();

	public static void main(String[] args) {
		new Thread(new Sheng(list, "������1��")).start();
		new Thread(new Sheng(list, "������2��")).start();
		new Thread(new Xiao(list, "������1��")).start();
		new Thread(new Xiao(list, "������2��")).start();
	}

	public static String ranStr() {
		StringBuilder str = new StringBuilder();
		String longStr = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
		int n = (int) (Math.random() * 5 + 1);
		for (int i = 0; i < n; i++)
			str.append(longStr.charAt((int) (Math.random() * 52)));
		return str.toString();
	}
}

class Sheng implements Runnable {
	private List<String> list;
	private String name;

	public Sheng(List<String> list, String name) {
		this.list = list;
		this.name = name;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (list) {
				while (list.size() >= 30)
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				String str = Test1.ranStr();
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Test1.list.add(str);
				System.out.println(name + "---������" + str + "������" + list.size() + "��");
				list.notifyAll();
			}
		}
	}
}

class Xiao implements Runnable {
	private List<String> list;
	private String name;

	public Xiao(List<String> list, String name) {
		this.list = list;
		this.name = name;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (list) {
				while (list.size() <= 0)
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				String str = list.remove(0);
				System.out.println(name + "---������" + str + "������" + list.size() + "��");
				list.notifyAll();
			}
		}
	}
}
